//
//  ST_NearbyForYouViewController.swift
//  btvideo
//
//  Created by mac on 2020/11/16.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import HandyJSON
import MJRefresh
import SwiftyJSON
import NIMSDK
import SwiftyUserDefaults
import RxSwift

/**
 附近活跃
 */
class ST_NearbyForYouViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
             
//        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: NSNotification.Name.init(ReceivedMatchNotificationKey), object: nil)
        binding()
        
    }
    
    private func binding(){
        
    
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.network_reachability_status, object: nil)
        
        SCComponets.location_component.loc_pushed_observer.observe(on: MainScheduler.instance).subscribe(onNext: { v in
            
            if v != nil {
                self.fetch_boot_data()
                print("订阅到 定位更新成功！！-- ST_NearbyForYouViewController")
            }
        }).disposed(by: rx.disposeBag)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f != true{
                own.clear_data()
            }
            
        }).disposed(by: rx.disposeBag)
                
    }
//    MARK: - request Data
    
    func waiting_for_fetch_boot() {
        
//  导致多调用一次接口 暂时不加
//        self.collectionView.mj_header?.beginRefreshing()
    }
    
    func fetch_boot_data() {
        
        self.refresh_data()
        
    }
    
    @objc fileprivate func refresh_data(){
        
        clear_data()
        request_data()
        
    }
    @objc func clear_data(){
        currentPage = 0
        self.data_array.removeAll()
        self.collectionView.reloadData()
    }
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,
                    "size":10]
        
        JVrequest(PH.nearbyActiveApi,parameters: param ,success: { (json) in
            
            print("附近活跃 数据:",json)
            
            
            
            var array = json["data"].arrayValue.map({ST_NearbyForYouCellModel.init(fromJson: $0)})

////                特质为空 样式， 数据不是4个的情况
//                if self.displaySupplement{
//                    array = array.filter({ (d) -> Bool in
//                        return d.feature_user.count >= 4
//                    })
//                }
                
            
            array.removeAll { (item) -> Bool in
                
                let exist = NIMSDK.shared().conversationManager.allRecentSessions()?.contains(where: {$0.session?.sessionId == item.accid })
                
                if let e = exist,e{
                    return true
                }
                return false
            }
                
            if self.currentPage == 1{
                self.data_array = array
            }else{
                self.data_array += array
            }
            
            self.collectionView.footer_refresh(count: array.count) {
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                    self?.request_data()
                })
            }
            
            self.collectionView.reloadData()
            
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            
        }) { (code, err) in
            
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            
            ToastHud(text: err, view: self.view)
        }
        
        
    }
//    MARK: - Properties
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
       let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 0
        controlLayout.minimumInteritemSpacing = 0
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.init(hex: 0xF8FAFC)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: NearbyForYouCell.self)
        
//        control.register(cellWithClass: PinterestGuidanceHomeCell.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 49, right: 0)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    fileprivate lazy var data_array = [ST_NearbyForYouCellModel]()
    
    
}


//MARK: - UICollection Delegate
extension ST_NearbyForYouViewController:UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let model = data_array[indexPath.item]
        
        let cell = collectionView.dequeueReusableCell(withClass: NearbyForYouCell.self, for: indexPath)
        
        cell.model = model
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return CGSize.init(width: ScreenWidth , height:  data_array[indexPath.item].cellHeight)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
     
        
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        let a = self.data_array.count - indexPath.row
        
        
        if a <= 8 {
            
            self.collectionView.mj_footer?.beginRefreshing()
            
        }
    }
}



//MARK: - Cell
class NearbyForYouCell: UICollectionViewCell {
    
    static let itemHeight = (ScreenWidth - 83 - 6 * 3 - 14)/4
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        
        contentView.addSubview(user_image_view)
        let userImageHeight = 58.cgFloat
        user_image_view.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().offset(15)
            make.width.height.equalTo(userImageHeight)
        }
        contentView.addSubview(icon_supplement_image_view)
        icon_supplement_image_view.snp.makeConstraints { (make) in
            make.center.equalTo(user_image_view)
            make.width.height.equalTo(78)
        }
        
        contentView.addSubview(green_point_view)
        green_point_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(12)
            make.bottom.equalTo(user_image_view)
            make.right.equalTo(user_image_view).offset(-5)
        }
        
        contentView.addSubview(nickname_label)
       
        nickname_label.snp.makeConstraints { (make) in
            make.left.equalTo(self.user_image_view.snp.right).offset(10)
            make.top.equalTo(user_image_view)
            make.height.equalTo(22)
            if ScreenWidth < 400{
                make.width.lessThanOrEqualTo(100)
            }else if ScreenWidth < 420{
                make.width.lessThanOrEqualTo(138)
            }
        }
        
        contentView.addSubview(sign_image_container)
        sign_image_container.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label.snp.right).offset(4)
            make.centerY.equalTo(nickname_label).offset(-1)
            make.height.equalTo(18)
            make.width.equalTo(70)
        }
        
        contentView.addSubview(distance_label)
        distance_label.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label)
            make.top.equalTo(nickname_label.snp.bottom).offset(1)
            make.height.equalTo(17)
        }
        
        
        contentView.addSubview(sign_label)
        sign_label.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label)
            make.right.equalToSuperview().offset(-66)
            make.top.equalTo(distance_label.snp.bottom).offset(1)
            make.height.equalTo(17)
        }
        
        let itemWidth = NearbyForYouCell.itemHeight
        contentView.addSubview(child_root_view)
        child_root_view.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label)
            make.right.equalToSuperview().offset(-14)
            make.top.equalTo(sign_label.snp.bottom).offset(10)
            make.height.equalTo(itemWidth)
        }
        
        contentView.addSubview(accost_btn)
        accost_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(48)
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(user_image_view)
        }

        contentView.addSubview(chat_btn)
        chat_btn.snp.makeConstraints { (make) in
            make.edges.equalTo(accost_btn)
        }
        
        contentView.addSubview(small_animate_view)
        small_animate_view.snp.makeConstraints { (make) in
            make.center.equalTo(accost_btn)
            make.width.equalTo(68)
        }
        
        var lastChildView:ST_NearbyForYouCellChildView?
        
        for _ in 0...3 {
            let control = ST_NearbyForYouCellChildView()
            child_root_view.addSubview(control)
            control.snp.makeConstraints { (make) in
                if let last = lastChildView{
                    make.left.equalTo(last.snp.right).offset(6)
                }else{
                    make.left.equalToSuperview()
                }
                make.width.height.equalTo(NearbyForYouCell.itemHeight)
                make.centerY.equalToSuperview()
            }
            
            lastChildView = control
            
            control.addTarget(self, action: #selector(preview_handle(sender:)), for: UIControl.Event.touchUpInside)
        }
      
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - Properties
    fileprivate lazy var user_image_view:UIImageView = {
        
        let control = UIImageView()
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 58/2.0
//        control.borderColor = Color.init(hexString: "#F2F4F7")
//        control.borderWidth = 2
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_user_center_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        return control
    }()

    fileprivate lazy var icon_supplement_image_view:UIImageView = {
        let control = UIImageView()
       control.contentMode = UIView.ContentMode.scaleAspectFill
       return control
    }()

    
    fileprivate lazy var green_point_view:UIView = {
       let control = UIView()
        control.alpha = 0
        control.backgroundColor = Color.init(hexString: "#22CF91")!
        control.borderColor = UIColor.white
        control.borderWidth = 1
        control.cornerRadius = 6
        return control
    }()
    
    fileprivate lazy var nickname_label:UILabel = {
       
        let control = UILabel()
        
        control.textColor = Color.init(hexString: "#333333")!
        
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        
        return control
    }()
    
    fileprivate lazy var sign_image_container:ST_UserSignView = {
        let control = ST_UserSignView()
        return control
    }()
    
    
    fileprivate lazy var distance_label:UILabel = {
       
        let control = UILabel()
        
        control.textColor = Color.init(hexString: "#999999")!
        
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        
        return control
    }()
    
    
    fileprivate lazy var sign_label:UILabel = {
       
        let control = UILabel()
        
        control.textColor = Color.init(hexString: "#999999")!
        
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        
        return control
    }()
    
    fileprivate lazy var accost_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.addTarget(self, action: #selector(right_btn_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    
    fileprivate lazy var small_animate_view:LOTAnimationView = {
            
        let path = Bundle.main.path(forResource: "搭讪小动画", ofType: "json")!
        
        let control = LOTAnimationView.init(filePath: path)
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.isUserInteractionEnabled = false
        control.alpha = 0
    
        return control
    }()
    
    
    
    fileprivate var sendHander:ST_DTChatMessageSendHander?
    
    fileprivate lazy var chat_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("nearbychat_icon")!)
        control.addTarget(self, action: #selector(right_btn_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    fileprivate var child_root_view = UIView()
    
    
    var model:ST_NearbyForYouCellModel?{
        didSet{
            
            guard let m = model else { return  }
            
            user_image_view.pin_setImage(from: m.avatar.compress_small_image(width: 60*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            nickname_label.text = m.nickname
            
            icon_supplement_image_view.pin_setImage(from: AVATAR_SUPPLEMENT(guardTime: m.guardTime, guardContent: m.guardContent)?.url)
            
            sign_image_container.bind_data(isVip: CHECK_MEMBER_STATUS(expirationTime: m.vipExpire) == .subscribe, detectedFace: m.faceAuditState == 3)
            
            distance_label.text = m.age.string + "岁  " + m.address
            
            sign_label.text = m.sign
            
            green_point_view.alpha = m.online_state.contains("现在活跃") ? 1 : 0
         
            if m.canAccost{
                accost_btn.alpha = 1
                small_animate_view.alpha = 1
                small_animate_view.animationProgress = m.isAccost ? 1 : 0
                chat_btn.alpha = 0
                accost_btn.isSelected = m.isAccost
            }else{
                accost_btn.alpha = 0
                small_animate_view.alpha = 0
                chat_btn.alpha = 1
            }
            
            for (idx,itemView) in child_root_view.subviews.enumerated(){
                
                if let v = itemView as? ST_NearbyForYouCellChildView,let child_model = m.feature[safe: idx]{
                    v.bind(url: child_model.content.compress_small_image(width: NearbyForYouCell.itemHeight*3), title: child_model.featureName, width: child_model.nameWidth)
                    itemView.isHidden = false
                }else{
                    itemView.isHidden = true
                }
            }
            
        }
    }
    
    @objc fileprivate func right_btn_handle(){
        
        guard let m = model else { return  }
        
        if m.canAccost{
            
            if accost_btn.isSelected{
                return
            }
            
            accost_handle()
            
            
            
            
        }else{
            
            push_to_chat_controller(info: ST_ChatInfoStruct.init(sessionId: m.accid, title: m.nickname, source: "个人主页"), navigationController: nil)
            
        }
        
    }
    
    @objc func accost_handle(){
        
        guard let m = model else { return  }
        
        self.accost_btn.isUserInteractionEnabled = false
        
        main_thread_execute(afterDelay: 1.5) {
            self.accost_btn.isUserInteractionEnabled = true
        }
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self.parentViewController) {
            return
        }
        
        ST_TianAccostManager.shared.accost(idSet: [m.accid], viewController: nil,success:  { (json) in
            
            self.model?.isAccost = true
            self.accost_btn.isSelected = true
            self.small_animate_view.play()
        })

        
        
    }
    
    @objc func preview_handle(sender:UIControl) {
        
        let index = self.child_root_view.subviews.firstIndex(where: {$0 == sender})
        
        guard let m = model,let idx = index?.uInt else { return  }
        
        var array = [ST_MWPhoto]()
         
        for model in m.feature{
         
         guard let url = model.content.url,let media = ST_MWPhoto.init(url:url ) else{
             
            array.append(ST_MWPhoto())
                continue
            }
            array.append(media)
        }
        
        guard let browser = ST_MWPhotoBrowser.init(photos: array) else{
            return
        }
        
        browser.displayActionButton = false;
        
         browser.setCurrentPhotoIndex(idx)
        
        let nav = UINavigationController.init(rootViewController: browser)
        
        GlobalPresent(toController: nav)
    }
    
    
    @objc fileprivate func push_user_center_handle(){
        
        guard let m = model else{
            return
        }
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = m.accid

        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
}



//MARK: -
class ST_NearbyForYouCellChildView: UIControl {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().offset(4)
            make.height.equalTo(16)
            make.width.equalTo(42)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 10
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.backgroundColor = .white
        control.cornerRadius = 8
        control.textColor = UIColor(hexString: "#333333")
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.medium)
        return control
    }()

    func bind(url:String,title:String,width:CGFloat) {
        
        cover_image_view.pin_setImage(from: url.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
        titleLabel.text = title
        
        titleLabel.snp.updateConstraints { (make) in
            make.width.equalTo(width)
        }
        
        
    }
    
    
    
}



//MARK: - Cell Model


class ST_NearbyForYouCellModel : NSObject {

    var accid : String
    var address : String
    var age : Int
    var avatar : String
    var birth : Int
    var faceAuditState : Int
    var feature : [ST_NearbyForYouFeatureModel]
    var guardContent : String
    var guardTime : Int
    var id : Int
    var nickname : String
    var sign : String
    var vdAddress : String
    var vipExpire : Int
    var online_state : String
    
    
    var cellHeight = NearbyForYouCell.itemHeight + 83 + 5
    var canAccost = false
    var isAccost = false
    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        accid = json["accid"].stringValue
        address = json["address"].stringValue
        age = json["age"].intValue
        avatar = json["avatar"].stringValue
        birth = json["birth"].intValue
        faceAuditState = json["face_audit_state"].intValue
        
        self.feature = json["feature"].arrayValue.map({ST_NearbyForYouFeatureModel.init(fromJson: $0)})
       
        guardContent = json["guard_content"].stringValue
        guardTime = json["guard_time"].intValue
        id = json["id"].intValue
        nickname = json["nickname"].stringValue
        sign = json["sign"].stringValue
        vdAddress = json["vd_address"].stringValue
        vipExpire = json["vip_expire"].intValue
        
        online_state = json["online_state"].stringValue
        
        if self.feature.count < 1{
            cellHeight -= NearbyForYouCell.itemHeight + 10
        }
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
            canAccost = true
        }
        super.init()
    }
}



class ST_NearbyForYouFeatureModel : NSObject {

    var featureName : String
    var content : String
    var nameWidth:CGFloat
    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        featureName = json["feature_name"].stringValue
        content = json["content"].stringValue
        nameWidth = featureName.width(withConstrainedHeight: 100, font: UIFont.systemFont(ofSize: 10, weight: .medium)) + 7*2
        super.init()
    }

}







//MARK: - 搭讪

class ST_TianAccostManager: NSObject {
    
//MARK: - init
    static let shared = ST_TianAccostManager()
    
    private override init() {
        super.init()
    }
    
    fileprivate var willSet = Set<String>()
    
    fileprivate weak var vc:UIViewController?
    
    fileprivate var successClosure:((JSON)->())?
    
    
    func accost(idSet:Set<String>,viewController:UIViewController?,success:@escaping (JSON)->())  {
        
        viewController?.show_indeterminate_h_u_d()
        
        willSet = idSet
        
        self.vc = viewController
        
        successClosure = success
        
        accost_loop()
        
    }
    
    fileprivate func accost_loop(){
        
        guard let targetAccid = willSet.first else{
            
            self.vc?.hidden_indeterminate_h_u_d()
            
            self.successClosure?(JSON.null)
            
            ST_ConversationAdapter.shared.refresh_all_data()
            
            return
        }
        
        JVrequest(PH.sendAccostChatGift,parameters: ["target_accid":targetAccid],success:  { (json) in
            
            
            let data = json["data"]
            
            ST_BTUserInfoManager.shared.additional_attributes?.freeAccostTime = data["free_chat_num"].intValue
            
            ST_BTUserInfoManager.shared.modify_sweet_coin(value: data["sweet_currency"].floatValue)
            
            let model = ST_DTChatMessage()
            
            model.chatID = targetAccid
            
            model.messageTime = Int64(Date().timeIntervalSince1970)
            
            model.cellStyle = .incomeGift
            
            model.direction = .send
            
            guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
            
            model.portraitUri = userInfo.avatar
            
            model.userName = userInfo.nickname
            
            let goods = ST_BTIMGiftMessageModel()
            
            goods.title = data["name"].stringValue
            goods.imageUrl = data["content"].stringValue
            goods.income = data["integral"].floatValue
//            let v = goodsModel.useCoin.float/10.0
            goods.subTitle = "+\(data["integral"].floatValue)\(Defaults[.PandaStr])"
            
            goods.type = ST_IMGoodsType.accost
            goods.logGiftId = data["gift_member_id"].stringValue
            model.goods = goods
            
//            model.uploadStatus = .success
            
            model.figureFrame()
            
            
            ST_DTChatMessageSendHander.shared.sendMessage(message: model)
          
            self.willSet.remove(targetAccid)
            
            if self.willSet.count > 0{
                
                self.accost_loop()
            }else{
                
                PlayFeedBack()
                ST_ConversationAdapter.shared.refresh_all_data()
                
                self.vc?.hidden_indeterminate_h_u_d()
                
                self.successClosure?(json)
            }
            
        },failure: { (code, err) in
            
            self.vc?.hidden_indeterminate_h_u_d()
                        
            if code == 10004{
                
                
                ST_MaidWayManager.shared.source = .搭讪充币
                
                ST_RechargeViewController.toast()
                
                return
            }
            
            self.vc?.toast(text: err)
            
        })
        
        
        
    }
    
    
}

//MARK: - 女性搭讪
class ST_TianFemaleAccostManager: NSObject {
    
    
//MARK: - init
    static let shared = ST_TianFemaleAccostManager()
    
    private override init() {
        super.init()
    }
    
    fileprivate var willSet = [JSON]()
    
    fileprivate var vc:UIViewController?
    
    fileprivate var successClosure:((JSON)->())?
    
    
    func accost(idSet:[JSON],viewController:UIViewController?,success:@escaping (JSON)->())  {
        
        viewController?.show_indeterminate_h_u_d()
        
        willSet = idSet
        
        self.vc = viewController
        
        successClosure = success
        
        accost_loop()
        
    }
    
    fileprivate  func accost_loop(){
        
        guard let target = willSet.first else{
            
            self.vc?.hidden_indeterminate_h_u_d()
            
            self.successClosure?(JSON.null)
            
            ST_ConversationAdapter.shared.refresh_all_data()
            
            return
        }
        
        
        
        JVrequest(PH.sendAccostChatGift,parameters: ["target_accid":target["accid"].stringValue],success:  { (json) in
            
            let model = ST_DTChatMessage()
            
            model.chatID = target["accid"].stringValue
            
            model.messageTime = Int64(Date().timeIntervalSince1970)
            
            model.cellStyle = .Text
            
            model.direction = .send
            
            guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
            
            model.portraitUri = userInfo.avatar
            
            model.userName = userInfo.nickname
            
            model.chatText = target["talk_message"].stringValue
            
//            model.uploadStatus = .success
            
            model.figureFrame()
            
            
            ST_DTChatMessageSendHander.shared.push_msg_to_i_m_service(message: model)
          
            if self.willSet.count > 0{
                self.willSet.removeFirst()
            }
            
            
            if self.willSet.count > 0{
                
                self.accost_loop()
            }else{
                
                PlayFeedBack()
                
                ST_ConversationAdapter.shared.refresh_all_data()
                
                self.vc?.hidden_indeterminate_h_u_d()
                
                self.successClosure?(json)
            }
            
        },failure: { (code, err) in
            
            self.vc?.hidden_indeterminate_h_u_d()
                        
            if code == 10004{
                
                ST_MaidWayManager.shared.source = .搭讪充币
                
                ST_RechargeViewController.toast()
                
                return
            }
            
            self.vc?.toast(text: err)
            
        })
        
        
        
    }
    
}
